﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess_Layer;
using Business_Layer;
using System.Collections;
public partial class MyAdmin_LoaiSanPham_AM : System.Web.UI.Page
{
    LogAction log=new LogAction();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenXem)
        { 
            // xử lý quyền xem
            ((CommandField)gvDSLoaiSanPham.Columns[0]).ShowDeleteButton = false;
            CommandField dtCmdField = ((CommandField)dtvLoaiSanPham.Fields[dtvLoaiSanPham.Fields.Count - 1]);
            dtCmdField.ShowEditButton = false;
            dtCmdField.ShowInsertButton = false;
            XoaNhieuBUTTON.Visible = false;
        }
        else if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenChinhSua)
        {
            // xử lý quyền chỉnh sửa
        }

        List<int> checkedCheckBoxRowIndex = getCheckedCheckBoxRowIndexes(gvDSLoaiSanPham);
        initDataSource();
        restoreCheckedCheckBox(checkedCheckBoxRowIndex);

        lblThongBaoDTView.Visible = false;
        lblThongBaoGridView.Visible = false;
    }

    private List<int> getCheckedCheckBoxRowIndexes(GridView gvDSNCC_GiangHang)
    {
        if (gvDSNCC_GiangHang.Rows.Count == 0)
        {
            return null;
        }
        
        List<int> rowIndexes = new List<int>();
        int lastCellIndex = gvDSLoaiSanPham.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSLoaiSanPham.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                rowIndexes.Add(r.RowIndex);
            }
        }

        return rowIndexes;
    }

    private void restoreCheckedCheckBox(List<int> checkedCheckBoxRowIndex)
    {
        if (checkedCheckBoxRowIndex == null)
        {
            return;
        }

        int lastCellIndex = gvDSLoaiSanPham.Rows[0].Cells.Count - 1;
        foreach (int rowIndex in checkedCheckBoxRowIndex)
        {
            ((CheckBox)gvDSLoaiSanPham.Rows[rowIndex].Cells[lastCellIndex].FindControl("checkXoa")).Checked = true;
        }
    }

    private void initDataSource()
    {
        refreshGV();
        gvDSLoaiSanPham.SelectedIndex = gvDSLoaiSanPham.SelectedIndex == -1 ? 0 : gvDSLoaiSanPham.SelectedIndex;
        dtvLoaiSanPham.PageIndex = Helper.calPageIndexForDetailView(gvDSLoaiSanPham);
    }

    protected void XoaNhieuBUTTON_Click(object sender, EventArgs e)
    {
        string ids = "";
        List<long> deletedIDs = new List<long>();
        int lastCellIndex = gvDSLoaiSanPham.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSLoaiSanPham.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                long id = long.Parse(r.Cells[2].Text);
                deletedIDs.Add(id);
                ids += id.ToString() + ", ";
            }
        }

        lblThongBaoGridView.Visible = true;
        lblThongBaoGridView.Text = "Xóa thành công record: " + ids.Substring(0, ids.LastIndexOf(", "));
        //log
        log.TenLoaiCapNhat = "Xóa";
        log.Ngay = DateTime.Now;
        log.TenBang = "Bảng Loại sản phẩm";
        log.TenLoaiDangNhap = "Admin";
        log.TenDangNhap = Helper.getCurrentAdminUserName(Session);
        string logText = "";
        log.DuLieuCu = "record ID:" + ids.Substring(0, ids.LastIndexOf(", "));
        logText = "X";
        log.DuLieuMoi = logText;
        Log_BUS.insert(log);
        //log
        try
        {
            DataAccess_Layer.Category_DAC.delete(deletedIDs);
        }
        catch (System.Exception ex)
        {
            lblThongBaoGridView.Text = "Xóa thất bại!";
        }

        initDataSource();
        refreshDetailViewPageIndex();
    }

    private void refreshGV()
    {
        gvDSLoaiSanPham.DataSource = DataAccess_Layer.Category_DAC.layHet();
        gvDSLoaiSanPham.DataBind();
    }

    private void refreshDetailViewPageIndex()
    {
        dtvLoaiSanPham.DataBind();
        dtvLoaiSanPham.PageIndex = Helper.calPageIndexForDetailView(gvDSLoaiSanPham);
    }

    protected void gvDSLoaiSanPham_PageIndexChanged(object sender, EventArgs e)
    {
         refreshDetailViewPageIndex();
    }

    protected void gvDSLoaiSanPham_SelectedIndexChanged(object sender, EventArgs e)
    {
        refreshDetailViewPageIndex();
    }

    protected void gvDSLoaiSanPham_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Helper.changeGVPageIndex(gvDSLoaiSanPham, e.NewPageIndex);
        gvDSLoaiSanPham.SelectedIndex = gvDSLoaiSanPham.Rows.Count > 0 ? 0 : -1;
        dtvLoaiSanPham.PageIndex = Helper.calPageIndexForDetailView(gvDSLoaiSanPham);
    }

    protected void dtvLoaiSanPham_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        refreshGV();
        Helper.changeGVPageIndex(gvDSLoaiSanPham, gvDSLoaiSanPham.PageCount - 1);
        gvDSLoaiSanPham.SelectedIndex = gvDSLoaiSanPham.Rows.Count - 1;
        refreshDetailViewPageIndex();
    }

    protected void dtvLoaiSanPham_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        refreshGV();
        refreshDetailViewPageIndex();
    }

    protected void btnUploadForEdit_Click(object sender, EventArgs e)
    {
        FileUpload fu = (FileUpload)dtvLoaiSanPham.FindControl("fuForEdit");
        Label statusLABEL = (Label)dtvLoaiSanPham.FindControl("lblUpdloadForEdit");
        TextBox tb = (TextBox)dtvLoaiSanPham.FindControl("txtUploadForEdit");

        try
        {
            string fullName = "";
            string filename = "images/LoaiSanPham/" + fu.FileName;
            fu.SaveAs(Server.MapPath("~/") + filename);
            fullName = "~/" + filename;
            tb.Text = fullName;
            statusLABEL.Text = "File đã được upload!";
        }
        catch (Exception ex)
        {
            statusLABEL.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }

    protected void cbbLSP_DataBound(object sender, EventArgs e)
    {
        DropDownList cbbLSP = (DropDownList)dtvLoaiSanPham.FindControl("cbbLSP");
        TextBox txtMaCLSP = (TextBox)dtvLoaiSanPham.FindControl("txtTenCLSP");

        if (dtvLoaiSanPham.CurrentMode == DetailsViewMode.Edit)
        {
            cbbLSP.SelectedValue = txtMaCLSP.Text;
        }
        else if (dtvLoaiSanPham.CurrentMode == DetailsViewMode.Insert)
        {
            txtMaCLSP.Text = cbbLSP.SelectedValue;
        }
    }

    protected void cbbLSP_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList cbbLSP = (DropDownList)dtvLoaiSanPham.FindControl("cbbLSP");
        TextBox txtMaCLSP = (TextBox)dtvLoaiSanPham.FindControl("txtTenCLSP");
        txtMaCLSP.Text = cbbLSP.SelectedValue;
    }

    protected void LQDSLoaiSanPham_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
        //log
        try
        {
            log.TenLoaiCapNhat = "Thêm";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Loại sản phẩm";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.Category logO;

            log.DuLieuCu = "X";

            logO = (DataAccess_Layer.Category)e.Result;
            log.DuLieuMoi = "Tên: " + logO.Name
                + "..\nHình: " + logO.Hinh
                + "..\nChủng loại sản phẩm: " + logO.MaChungLoaiSP
                + "..\nđã xóa: " + logO.DaXoa;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        lblThongBaoDTView.Visible = true;
        DataAccess_Layer.Category newOrder = (DataAccess_Layer.Category)e.Result;

        if (e.Exception == null)
        {
            lblThongBaoDTView.Text = "Thêm thành công record có ID là " + newOrder.ID;
            return;
        }

        lblThongBaoDTView.Text = "Thêm thất bại record!";
        e.ExceptionHandled = true;
    }
    protected void LQDSLoaiSanPham_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = gvDSLoaiSanPham.DataSource;
    }
    protected void LQDSLoaiSanPham_Updating(object sender, LinqDataSourceUpdateEventArgs e)
    {
        //log
        try
        {
            log.TenLoaiCapNhat = "cập nhật";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Loại sản phẩm";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.Category logO = (DataAccess_Layer.Category)e.OriginalObject;

            log.DuLieuCu = "Tên: " + logO.Name
                + "..\nHình: " + logO.Hinh
                + "..\nChủng loại sản phẩm: " + logO.MaChungLoaiSP
                + "..\nđã xóa: " + logO.DaXoa;



            logO = (DataAccess_Layer.Category)e.NewObject;
            log.DuLieuCu = "Tên: " + logO.Name
                 + "..\nHình: " + logO.Hinh
                 + "..\nChủng loại sản phẩm: " + logO.MaChungLoaiSP
                 + "..\nđã xóa: " + logO.DaXoa;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        DataAccess_Layer.Category newOrder = (DataAccess_Layer.Category)e.NewObject;

        lblThongBaoDTView.Visible = true;
        try
        {
            DataAccess_Layer.Category_DAC.update(newOrder);
            lblThongBaoDTView.Text = "Cập nhật thành công record có ID là " + newOrder.ID;
        }
        catch (System.Exception ex)
        {
            lblThongBaoDTView.Text = "Cập nhật thất bại record có ID là " + newOrder.ID;
        }

        e.Cancel = true;
    }
}